package com.dz.risk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dz.risk.common.ExcelUtils;
import com.dz.risk.common.ResponseVO;
import com.dz.risk.common.SysConstant;
import com.dz.risk.common.exception.RRException;
import com.dz.risk.dao.RiskFactorDao;
import com.dz.risk.dao.RiskFactorValueDao;
import com.dz.risk.pojo.QueryParams;
import com.dz.risk.pojo.domain.ReportCodeLocatingTemplateEntity;
import com.dz.risk.pojo.domain.RiskFactorEntity;
import com.dz.risk.pojo.domain.RiskFactorValueEntity;
import com.dz.risk.pojo.domain.TemporaryTableOfDataEntity;
import com.dz.risk.service.RiskFactorValueService;
import com.dz.risk.service.TemporaryTableOfDataService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


@Service
public class RiskFactorValueServiceImpl extends ServiceImpl<RiskFactorValueDao, RiskFactorValueEntity> implements RiskFactorValueService {

    @Autowired
    RiskFactorValueDao riskFactorValueDao;

    @Autowired
    RiskFactorDao riskFactorDao;

    @Autowired
    TemporaryTableOfDataService temporaryTableOfDataService;

    @Override
    public PageInfo<RiskFactorValueEntity> queryFactorAndValue(QueryParams queryParams) throws RRException {
        PageHelper.startPage(queryParams.getPageNum(), queryParams.getPageSize());
        List<RiskFactorValueEntity> riskFactorValueEntities = riskFactorValueDao.queryFactorAndValue(queryParams.getInitDate());
        return new PageInfo<>(riskFactorValueEntities);
    }

    @Override
    public ResponseVO importRiskFactorValue(Workbook wb, Integer excelType, String date) throws RRException {
        Sheet sheet1 = wb.getSheetAt(SysConstant.ZERO);
        //拿到这表的总行数
        int lastRowNum = sheet1.getLastRowNum();
        if (lastRowNum == SysConstant.ZERO) {
            return ResponseVO.fail("Please fill in data before importing");
        }
        return getSheetValue(lastRowNum, sheet1, excelType, date);
    }

    /**
     * 读取excel表格数据
     *
     * @param lastRowNum
     * @param sheet1
     */
    public ResponseVO getSheetValue(int lastRowNum, Sheet sheet1, Integer excelType, String date)
            throws RRException {
        for (int i = 2; i <= lastRowNum; i++) {
            //拿到每一行,从第三行开始
            Row row = sheet1.getRow(i);
            Cell riskContent = row.getCell(0);
            // 判断该风险因子是否存在,如果不存在直接返回错误信息
            if (riskContent == null) {
                return ResponseVO.fail("Risk factors cant null");
            }
            LambdaQueryWrapper<RiskFactorEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RiskFactorEntity::getRiskContent, riskContent.getStringCellValue());
            RiskFactorEntity db = riskFactorDao.selectOne(queryWrapper);
            if (db == null) {
                return ResponseVO.fail("Risk factors not exist");
            }

            final String numberPrefix = "M{";
            final String numberSuffix = "}";
            Long versionDate = Long.parseLong(date.replace("-", ""));
            // 如果导入模板
            if (excelType == 1) {
                String oneMonthsMildCodeCellValue = String.valueOf(ExcelUtils.getCellValue(row.getCell(1)));
                if (!StringUtils.isEmpty(oneMonthsMildCodeCellValue) && oneMonthsMildCodeCellValue.contains(numberPrefix)) {
                    //去除编码前后缀得到纯编码
                    oneMonthsMildCodeCellValue = oneMonthsMildCodeCellValue.replace(numberPrefix, "").replace(numberSuffix, "").trim();
                }
                db.setInTheNextOneMonthsMildCode(oneMonthsMildCodeCellValue);

                String oneMonthsModerateCodeCellValue = String.valueOf(ExcelUtils.getCellValue(row.getCell(2)).toString());
                if (!StringUtils.isEmpty(oneMonthsModerateCodeCellValue) && oneMonthsModerateCodeCellValue.contains(numberPrefix)) {
                    //去除编码前后缀得到纯编码
                    oneMonthsModerateCodeCellValue = oneMonthsModerateCodeCellValue.replace(numberPrefix, "").replace(numberSuffix, "").trim();
                }
                db.setInTheNextOneMonthsModerateCode(oneMonthsModerateCodeCellValue);

                String oneMonthsSevereCodeCellValue = String.valueOf(ExcelUtils.getCellValue(row.getCell(3)).toString());
                if (!StringUtils.isEmpty(oneMonthsSevereCodeCellValue) && oneMonthsSevereCodeCellValue.contains(numberPrefix)) {
                    //去除编码前后缀得到纯编码
                    oneMonthsSevereCodeCellValue = oneMonthsSevereCodeCellValue.replace(numberPrefix, "").replace(numberSuffix, "").trim();
                }
                db.setInTheNextOneMonthsSevereCode(oneMonthsSevereCodeCellValue);

                String twoMonthsMildCodeCellValue = String.valueOf(ExcelUtils.getCellValue(row.getCell(4)).toString());
                if (!StringUtils.isEmpty(twoMonthsMildCodeCellValue) && twoMonthsMildCodeCellValue.contains(numberPrefix)) {
                    //去除编码前后缀得到纯编码
                    twoMonthsMildCodeCellValue = twoMonthsMildCodeCellValue.replace(numberPrefix, "").replace(numberSuffix, "").trim();
                }
                db.setInTheNextTwoMonthsMildCode(twoMonthsMildCodeCellValue);

                String twoMonthsModerateCodeCellValue = String.valueOf(ExcelUtils.getCellValue(row.getCell(5)).toString());
                if (!StringUtils.isEmpty(twoMonthsModerateCodeCellValue) && twoMonthsModerateCodeCellValue.contains(numberPrefix)) {
                    //去除编码前后缀得到纯编码
                    twoMonthsModerateCodeCellValue = twoMonthsModerateCodeCellValue.replace(numberPrefix, "").replace(numberSuffix, "").trim();
                }
                db.setInTheNextTwoMonthsModerateCode(twoMonthsModerateCodeCellValue);

                String twoMonthsSevereCodeCellValue = String.valueOf(ExcelUtils.getCellValue(row.getCell(6)).toString());
                if (!StringUtils.isEmpty(twoMonthsSevereCodeCellValue) && twoMonthsSevereCodeCellValue.contains(numberPrefix)) {
                    //去除编码前后缀得到纯编码
                    twoMonthsSevereCodeCellValue = twoMonthsSevereCodeCellValue.replace(numberPrefix, "").replace(numberSuffix, "").trim();
                }
                db.setInTheNextTwoMonthsSevereCode(twoMonthsSevereCodeCellValue);

                String threeMonthsMildCodeCellValue = String.valueOf(ExcelUtils.getCellValue(row.getCell(7)).toString());
                if (!StringUtils.isEmpty(threeMonthsMildCodeCellValue) && threeMonthsMildCodeCellValue.contains(numberPrefix)) {
                    //去除编码前后缀得到纯编码
                    threeMonthsMildCodeCellValue = threeMonthsMildCodeCellValue.replace(numberPrefix, "").replace(numberSuffix, "").trim();
                }
                db.setInTheNextThreeMonthsMildCode(threeMonthsMildCodeCellValue);

                String threeMonthsModerateCodeCellValue = String.valueOf(ExcelUtils.getCellValue(row.getCell(8)).toString());
                if (!StringUtils.isEmpty(threeMonthsModerateCodeCellValue) && threeMonthsModerateCodeCellValue.contains(numberPrefix)) {
                    //去除编码前后缀得到纯编码
                    threeMonthsModerateCodeCellValue = threeMonthsModerateCodeCellValue.replace(numberPrefix, "").replace(numberSuffix, "").trim();
                }
                db.setInTheNextThreeMonthsModerateCode(threeMonthsModerateCodeCellValue);

                String threeMonthsSevereCodeCellValue = String.valueOf(ExcelUtils.getCellValue(row.getCell(9)).toString());
                if (!StringUtils.isEmpty(threeMonthsSevereCodeCellValue) && threeMonthsSevereCodeCellValue.contains(numberPrefix)) {
                    //去除编码前后缀得到纯编码
                    threeMonthsSevereCodeCellValue = threeMonthsSevereCodeCellValue.replace(numberPrefix, "").replace(numberSuffix, "").trim();
                }
                db.setInTheNextThreeMonthsSevereCode(threeMonthsSevereCodeCellValue);
                riskFactorDao.updateById(db);
            } else {
                if(StringUtils.isEmpty(db.getInTheNextOneMonthsMildCode()) || StringUtils.isEmpty(db.getInTheNextOneMonthsModerateCode()) || StringUtils.isEmpty(db.getInTheNextOneMonthsSevereCode())
                 || StringUtils.isEmpty(db.getInTheNextTwoMonthsMildCode()) || StringUtils.isEmpty(db.getInTheNextTwoMonthsModerateCode()) || StringUtils.isEmpty(db.getInTheNextTwoMonthsSevereCode())
                 || StringUtils.isEmpty(db.getInTheNextThreeMonthsMildCode()) || StringUtils.isEmpty(db.getInTheNextThreeMonthsModerateCode()) || StringUtils.isEmpty(db.getInTheNextThreeMonthsSevereCode())){
                    return ResponseVO.fail("风险因子发生变化,请重新下载模板导入模板");
                }
                // 如果是导入数据
                RiskFactorValueEntity riskFactorValueEntity = new RiskFactorValueEntity();

                List<TemporaryTableOfDataEntity> temporaryTableOfDataEntities = new ArrayList<>();
                Object vale = new Object();
                TemporaryTableOfDataEntity temporaryTableOfDataEntity = new TemporaryTableOfDataEntity();
                riskFactorValueEntity.setRiskCode(db.getRiskCode());
                riskFactorValueEntity.setVersion(date);

                // 未来一个月轻度 如果没有填写默认为0 如果填写取小数点后两位
                Cell inTheNextOneMonthsMild = row.getCell(1);
                vale = ExcelUtils.getCellValueForNumber(inTheNextOneMonthsMild);
                if (vale.equals("")) {
                    vale = SysConstant.ZERO;
                }
                riskFactorValueEntity.setInTheNextOneMonthsMild(vale.toString());
                temporaryTableOfDataEntity.setIndexId(db.getInTheNextOneMonthsMildCode());
                temporaryTableOfDataEntity.setIndexValue(vale.toString());
                temporaryTableOfDataEntity.setDate(versionDate);
                temporaryTableOfDataEntities.add(temporaryTableOfDataEntity);

                // 未来一个月中度
                Cell inTheNextOneMonthsModerate = row.getCell(2);
                vale = ExcelUtils.getCellValueForNumber(inTheNextOneMonthsModerate);
                if (vale.equals("")) {
                    vale = SysConstant.ZERO;
                }
                riskFactorValueEntity.setInTheNextOneMonthsModerate(vale.toString());
                temporaryTableOfDataEntity = new TemporaryTableOfDataEntity();
                temporaryTableOfDataEntity.setIndexId(db.getInTheNextOneMonthsModerateCode());
                temporaryTableOfDataEntity.setIndexValue(vale.toString());
                temporaryTableOfDataEntity.setDate(versionDate);
                temporaryTableOfDataEntities.add(temporaryTableOfDataEntity);

                // 未来一个月重度
                Cell inTheNextOneMonthsSevere = row.getCell(3);
                vale = ExcelUtils.getCellValueForNumber(inTheNextOneMonthsSevere);
                if (vale.equals("")) {
                    vale = SysConstant.ZERO;
                }
                riskFactorValueEntity.setInTheNextOneMonthsSevere(vale.toString());
                temporaryTableOfDataEntity = new TemporaryTableOfDataEntity();
                temporaryTableOfDataEntity.setIndexId(db.getInTheNextOneMonthsSevereCode());
                temporaryTableOfDataEntity.setIndexValue(vale.toString());
                temporaryTableOfDataEntity.setDate(versionDate);
                temporaryTableOfDataEntities.add(temporaryTableOfDataEntity);

                // 未来两个月轻度
                Cell inTheNextTwoMonthsMild = row.getCell(4);
                vale = ExcelUtils.getCellValueForNumber(inTheNextTwoMonthsMild);
                if (vale.equals("")) {
                    vale = SysConstant.ZERO;
                }
                riskFactorValueEntity.setInTheNextTwoMonthsMild(vale.toString());
                temporaryTableOfDataEntity = new TemporaryTableOfDataEntity();
                temporaryTableOfDataEntity.setIndexId(db.getInTheNextTwoMonthsMildCode());
                temporaryTableOfDataEntity.setIndexValue(vale.toString());
                temporaryTableOfDataEntity.setDate(versionDate);
                temporaryTableOfDataEntities.add(temporaryTableOfDataEntity);

                // 未来两个月中度
                Cell inTheNextTwoMonthsModerate = row.getCell(5);
                vale = ExcelUtils.getCellValueForNumber(inTheNextTwoMonthsModerate);
                if (vale.equals("")) {
                    vale = SysConstant.ZERO;
                }
                riskFactorValueEntity.setInTheNextTwoMonthsModerate(vale.toString());
                temporaryTableOfDataEntity = new TemporaryTableOfDataEntity();
                temporaryTableOfDataEntity.setIndexId(db.getInTheNextTwoMonthsModerateCode());
                temporaryTableOfDataEntity.setIndexValue(vale.toString());
                temporaryTableOfDataEntity.setDate(versionDate);
                temporaryTableOfDataEntities.add(temporaryTableOfDataEntity);

                // 未来两个月重度
                Cell inTheNextTwoMonthsSevere = row.getCell(6);
                vale = ExcelUtils.getCellValueForNumber(inTheNextTwoMonthsSevere);
                if (vale.equals("")) {
                    vale = SysConstant.ZERO;
                }
                riskFactorValueEntity.setInTheNextTwoMonthsSevere(vale.toString());
                temporaryTableOfDataEntity = new TemporaryTableOfDataEntity();
                temporaryTableOfDataEntity.setIndexId(db.getInTheNextTwoMonthsSevereCode());
                temporaryTableOfDataEntity.setIndexValue(vale.toString());
                temporaryTableOfDataEntity.setDate(versionDate);
                temporaryTableOfDataEntities.add(temporaryTableOfDataEntity);

                // 未来三个月轻度
                Cell inTheNextThreeMonthsMild = row.getCell(7);
                vale = ExcelUtils.getCellValueForNumber(inTheNextThreeMonthsMild);
                if (vale.equals("")) {
                    vale = SysConstant.ZERO;
                }
                riskFactorValueEntity.setInTheNextThreeMonthsMild(vale.toString());
                temporaryTableOfDataEntity = new TemporaryTableOfDataEntity();
                temporaryTableOfDataEntity.setIndexId(db.getInTheNextThreeMonthsMildCode());
                temporaryTableOfDataEntity.setIndexValue(vale.toString());
                temporaryTableOfDataEntity.setDate(versionDate);
                temporaryTableOfDataEntities.add(temporaryTableOfDataEntity);

                // 未来三个月中度
                Cell inTheNextThreeMonthsModerate = row.getCell(8);
                vale = ExcelUtils.getCellValueForNumber(inTheNextThreeMonthsModerate);
                if (vale.equals("")) {
                    vale = SysConstant.ZERO;
                }
                riskFactorValueEntity.setInTheNextThreeMonthsModerate(vale.toString());
                temporaryTableOfDataEntity = new TemporaryTableOfDataEntity();
                temporaryTableOfDataEntity.setIndexId(db.getInTheNextThreeMonthsModerateCode());
                temporaryTableOfDataEntity.setIndexValue(vale.toString());
                temporaryTableOfDataEntity.setDate(versionDate);
                temporaryTableOfDataEntities.add(temporaryTableOfDataEntity);

                // 未来三个月重度
                Cell inTheNextThreeMonthsSevere = row.getCell(9);
                vale = ExcelUtils.getCellValueForNumber(inTheNextThreeMonthsSevere);
                if (vale.equals("")) {
                    vale = SysConstant.ZERO;
                }
                riskFactorValueEntity.setInTheNextThreeMonthsSevere(vale.toString());
                temporaryTableOfDataEntity = new TemporaryTableOfDataEntity();
                temporaryTableOfDataEntity.setIndexId(db.getInTheNextThreeMonthsSevereCode());
                temporaryTableOfDataEntity.setIndexValue(vale.toString());
                temporaryTableOfDataEntity.setDate(versionDate);
                temporaryTableOfDataEntities.add(temporaryTableOfDataEntity);
                this.save(riskFactorValueEntity);
                temporaryTableOfDataService.saveBatch(temporaryTableOfDataEntities);
            }
        }
        return ResponseVO.ok();
    }

    @Override
    public void updateThreadFlag(String initDate) {
        riskFactorValueDao.updateThreadFlag(initDate);
    }
}